// pages/comment/comment.js
import {
  isFullScreen,
  placeholderArr,
  timeSpan
} from '../../utils/util.js';

import {
  CommentModel
} from '../../models/comment.js';

import {
  Lock
} from '../../models/lock.js';

import {
  Log
} from '../../utils/log.js';

import {
  Token
} from '../../utils/token.js';

const token = new Token();

const lock = new Lock();

const log = new Log();

const comment = new CommentModel();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isFullScreen: isFullScreen(),
    openKeyword: true,
    focus: true,
    inputValue: '',
    placeholder: placeholderArr(),
    comments: [],
    replyData: {},
    activeReply: false,
    pageIndex: 1,
    loadMore: {
      "show": false,
      "type": "loading"
    },
    commentTotal: 0,
    loadingHidden: true,
    logData: {
      "contentId": 0,
      "content": "",
      // 分类ID
      "categoryId": 0
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      contentId: options.contentId,
      logData: {
        "contentId": options.contentId,
      }
    })

    token.verify().then(res => {
      if (res) {
        this._loadData();
      }
    });
  },

  _loadData() {
    let that = this;
    comment.getCommentsByContentId(that.data.contentId, that.data.pageIndex).then(res => {

      // 添加评论总数量
      that.setData({
        commentTotal: res.data.rootTotal
      })

      // 加载数据
      if (res.data.result.length > 0) {

        res.data.result.forEach(e => {
          e.createTime = timeSpan(e.createTime);
        })

        //数组合并
        that.data.comments.push.apply(that.data.comments, res.data.result);
        that.setData({
          comments: that.data.comments
        });
      }

      // 关闭评论加载提示
      wx.hideLoading();

      // 关闭底部触底提示
      that._closeLoadMoreTip();

      // 关闭骨架
      that._closeSkeletonView();
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //this._loadData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.comments.length == this.data.commentTotal) {
      // 加载全部
      this._showLoadedAllTip();
    } else {
      this.data.pageIndex++;
      this._showLoadMoreTip();
      this._loadData();
    }
  },
  onComment() {
    this._openKeyword();
  },
  bindKeyInput: function (e) {
    this.setData({
      inputValue: e.detail.value
    })
  },
  sendComment() {
    if (!this.data.inputValue) {
      this._closeKeyword();
      return;
    }

    if (this.data.activeReply) { // 回复状态
      let param = this.data.replyData;
      param.content = this.data.inputValue;
      comment.operate(param, "reply").then(res => {
        this._closeKeyword();

        if (!res.data.result) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          });
        } else {
          setTimeout(() => {
            wx.showLoading({
              title: '评论成功',
            });
            this.data.logData.content = param.content;
            this._reportAnalysis();
            this._reload();
          }, 600);
        }
      })
    } else {
      let param = {
        "content": this.data.inputValue,
        "contentId": this.data.contentId
      }
      comment.operate(param).then(res => {
        this._closeKeyword();
        if (!res.data.result) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          });
        } else {
          setTimeout(() => {
            wx.showLoading({
              title: '评论成功',
            });
            this.data.logData.content = param.content;
            this._reportAnalysis();
            this._reload();
          }, 600);
        }
      })
    }
  },
  onPopup() {
    this._closeKeyword();
  },
  _openKeyword() {
    this.setData({
      openKeyword: true,
      focus: true
    })
  },
  _closeKeyword() {
    this.setData({
      openKeyword: false,
      focus: false,
      inputValue: '',
      replyData: {},
      activeReply: false,
      placeholder: placeholderArr()
    })
  },
  onReply(e) {

    let detail = e.detail;

    let param = {
      "contentId": this.data.contentId,
      "replyId": detail.userId,
      "parentCommentId": detail.id
    }

    this.setData({
      replyData: param,
      activeReply: true,
      placeholder: "回复 : " + detail.nickName
    })

    this._openKeyword();
  },
  onMore(e) {
    let param = e.detail;
    wx.navigateTo({
      url: `../reply/reply?commentId=${param.id}`,
    })
  },
  _showLoadedAllTip() {
    this.setData({
      loadMore: {
        "show": true,
        "type": "end"
      }
    })
  },
  _showLoadMoreTip() {
    this.setData({
      loadMore: {
        "show": true,
        "type": "loading"
      }
    })
  },
  _closeLoadMoreTip() {
    this.setData({
      loadMore: {
        "show": false,
        "type": "loading"
      }
    })
  },
  _closeSkeletonView() {
    this.setData({
      loadingHidden: false
    });
  },
  /**
   * 评论之后页面初始化
   */
  _commented() {
    this._closeLoadMoreTip();
    this.setData({
      comments: [],
      pageIndex: 1
    })
  },
  _reload() {
    this._commented();
    this._loadData();
  },
  onLike(e) {

    let liked = e.detail.liked;
    let commentId = e.detail.id;
    let index = e.detail.index;

    if (lock.isLocked()) {
      return;
    }

    // 加锁
    lock.lock();

    if (liked) {
      comment.unlike(commentId).then(res => {
        this._refreshComment(index, res.data);
        lock.unlock();
      }).catch(err => {
        lock.unlock();
      });
    } else {
      comment.like(commentId).then(res => {
        this._refreshComment(index, res.data);
        lock.unlock();
      }).catch(err => {
        lock.unlock();
      });
    }
  },
  _refreshComment(index, comment) {
    setTimeout(() => {
      this.data.comments[index].praiseNum = comment.praiseNum;
      this.data.comments[index].liked = comment.like;
      this.setData({
        comments: this.data.comments
      })
    }, 600);
  },
  onDel(e) {

    let that = this;
    let commentId = e.detail.id;
    let contentId = e.detail.contentId;
    let index = e.detail.index;

    if (lock.isLocked()) {
      return;
    }

    // 加锁
    lock.lock();

    wx.showModal({
      title: '提示',
      content: '确定要删除吗？',
      success: function (sm) {
        if (sm.confirm) {
          comment.delete(contentId, commentId).then(res => {
            if (res.data) {
              that.data.comments.splice(index, 1);
              that.setData({
                comments: that.data.comments,
                commentTotal: that.data.commentTotal - 1
              })
              lock.unlock();
            }
          }).catch(err => {
            lock.unlock();
          });
        } else if (sm.cancel) {
          lock.unlock();
        }
      }
    })
  },
  onChildDel(e) {

    let that = this;
    let commentId = e.detail.id;
    let contentId = e.detail.contentId;
    let pIndex = e.detail.parentIndex;
    let cIndex = e.detail.childIndex;

    if (lock.isLocked()) {
      return;
    }

    // 加锁
    lock.lock();

    wx.showModal({
      title: '提示',
      content: '确定要删除吗？',
      success: function (sm) {
        if (sm.confirm) {
          comment.delete(contentId, commentId).then(res => {
            if (res.data) {
              that.data.comments[pIndex].children.splice(cIndex, 1);
              that.setData({
                comments: that.data.comments,
              })
              lock.unlock();
            }
          }).catch(err => {
            lock.unlock();
          });
        } else if (sm.cancel) {
          lock.unlock();
        }
      }
    })
  },
  _reportAnalysis() {
    log.logComment(this.data.logData);
  }
})